<template>
  <div class="create-stock-in">
    <el-form ref="form" :model="formData" label-width="120px">
      <el-form-item label="供应商">
        <el-select v-model="formData.supplier" placeholder="请选择供应商">
          <el-option
            v-for="item in suppliers"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="商品明细">
        <el-table :data="formData.details" border>
          <el-table-column prop="product" label="商品">
            <template #default="{ row }">
              <el-select v-model="row.product" placeholder="请选择商品">
                <el-option
                  v-for="product in products"
                  :key="product.id"
                  :label="product.name"
                  :value="product.id"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column prop="price" label="单价">
            <template #default="{ row }">
              <el-input-number v-model="row.price" :precision="2" />
            </template>
          </el-table-column>
          <el-table-column prop="quantity" label="数量">
            <template #default="{ row }">
              <el-input-number v-model="row.quantity" />
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="{ $index }">
              <el-button @click="removeDetail($index)" type="danger" circle>−</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button @click="addDetail" type="primary">添加商品</el-button>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm">提交</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import request from '@/utils/request'
import { ElMessage } from 'element-plus'

const formData = ref({
  supplier: null,
  details: [
    { product: null, price: 0, quantity: 1 }
  ]
})

const suppliers = ref([])
const products = ref([])

const getSuppliers = async () => {
  const res = await request.get('/supplier/')
  suppliers.value = res.records
}

const getProducts = async () => {
  const res = await request.get('/product/')
  products.value = res.records
}

const addDetail = () => {
  formData.value.details.push({ product: null, price: 0, quantity: 1 })
}

const removeDetail = (index) => {
  formData.value.details.splice(index, 1)
}

const submitForm = async () => {
  try {
    await request.post('/stock-in/', formData.value)
    ElMessage.success('创建成功')
  } catch (error) {
    ElMessage.error('创建失败')
  }
}

getSuppliers()
getProducts()
</script>
